<template>
  <div class="my">
    <!-- 顶部导航栏 -->
    <Navbar>
      <template #left>
        <div class="back-btn" @click="handleBack">
          <Icon name="zuojiantou" color="#fff" size="18"></Icon>
        </div>
      </template>
    </Navbar>

    <!-- 背景图片区域（可下拉放大） -->
    <div class="my_title_background" :style="{
      height: backgroundHeight + 'px',
      transform: `scale(${backgroundScale})`,
      opacity: backgroundOpacity,
      '--scale': backgroundScale
    }">
      <img class="background" src="http://43.138.15.137:8080/assets/img/281578538336_.pic_hd.e816ad71.jpg" alt="">
    </div>

    <!-- 用户信息与内容主体 -->
    <div class="profile" @touchstart.passive="handleTouchStart" @touchmove.passive="handleTouchMove"
      @touchend.passive="handleTouchEnd" @mousedown="handleMouseDown"
      :style="{ transform: `translate(0px, 0px) scale(1) translateZ(0px)` }">
      <!-- 头像 -->
      <div class="avatar_wrap">
        <img class="avatar" :src="friendUserInfo.userAvatar" alt="">
      </div>

      <!-- 昵称 & 抖音号 & 关注按钮 -->
      <div class="name_wrap">
        <div class="name">{{ friendUserInfo.userNickname }}</div>
        <div class="subname">抖音号: {{ friendUserInfo.userId }}</div>
        <div class="foolw" :class="{ 'active': friendUserInfo.myRelation == 'follow' || friendUserInfo.myRelation == 'both' }" @click="handlfollowUser">
          <div class="foolw_btn">
            {{ friendUserInfo.myRelation == 'both' ? '相互关注' : 
               friendUserInfo.myRelation == 'follow' ? '已关注' : 
               friendUserInfo.myRelation == 'follower' ? '回关' : '关注' }}
          </div>
        </div>
      </div>

      <!-- 用户描述信息：性别、年龄、地址 -->
      <div class="desc_wrap">
        <div class="desc">{{ friendUserInfo.userDesc }}</div>
        <div class="desc_wrap_info">
          <div class="gender">
            <Icon :name="friendUserInfo.userGender === '男' ? 'nanxing' : 'women-line'" size="12"
              :color="friendUserInfo.userGender === '男' ? '#448fe0' : '#ec407a'" />
            <span>{{ friendUserInfo.userGender === '男' ? '男' : '女' }}</span>
          </div>
          <div class="desc_wrap_info_age"><span>{{ friendUserInfo.userAge }}岁</span></div>
          <div class="desc_wrap_info_address"><span>{{ friendUserInfo.userAddress }}</span></div>
        </div>
      </div>

      <!-- 统计数据：获赞、关注、粉丝 -->
      <div class="num_wrap">
        <div class="li">获赞{{ likeNum }}</div>
        <div class="li" @click="handleGoTAfollow">关注{{ followNum }}</div>
        <div class="li" @click="handleGoTAfans">粉丝{{ fanNum }}</div>
      </div>

      <!-- 内容 Tabs：作品 / 动态 / 喜欢 -->
      <Tab :key="tabKey" @change="handleTabChange">

        <!-- Tab 1: 作品 -->
        <TabItem :title="`作品${dynamicNum}`">
          <!-- 加载中 -->
          <div v-if="tabLoading.work" class="tab-loading">
            <span class="icon">
              <Icon name="jiazailoadding" color="red" size="24" />
            </span>
            <span>加载中...</span>
          </div>
          <!-- 无数据或超时 -->
          <div v-else-if="tabTimeout.work || friendUserVideos.length === 0" class="tab-no-data">暂无作品</div>
          <!-- 正常显示 -->
          <div v-else class="tab_list">
            <div class="tab_list_item" v-for="(item, index) in friendUserVideos" :key="item.videoId"
              @click="handleClickWork(index)">
              <img :src="item.videoCover" alt="" />
              <div class="tab_list_item__like">
                <Icon name="xin-2" size="14" color="#ccc" />
                <span>{{ item.likeNum }}</span>
              </div>
            </div>
          </div>
        </TabItem>

        <!-- Tab 2: 动态 -->
        <TabItem :title="`动态${dynamicNum}`">
          <!-- 加载中 -->
          <div v-if="tabLoading.dynamic" class="tab-loading">
            <span class="icon">
              <Icon name="jiazailoadding" color="red" size="24" />
            </span>
            <span>加载中...</span>
          </div>
          <!-- 无数据或超时 -->
          <div v-else-if="tabTimeout.dynamic || dynamicList.length === 0" class="tab-no-data">暂无动态</div>

          <!-- 动态内容 -->
          <div class="follow-page">
            <div class="post-item" v-for="(item, index) in dynamicList" :key="item.videoId">
              <!-- 发布者信息 -->
              <div class="post-header">
                <img :src="item.userAvatar" alt="avatar" class="avatar" />
                <span class="username">@{{ item.userNickname }}</span>
              </div>

              <!-- 文案描述 -->
              <div class="post-meta">{{ item.videoDesc }}</div>

              <!-- 视频媒体区（点击切换播放状态） -->
              <div class="post-media" @click="togglePlay(index)">
                <video ref="videoRefs" class="media-video" :src="item.videoPath" preload="metadata" playsinline
                  webkit-playsinline x5-playsinline loop :muted="false"></video>
                <!-- 播放/暂停覆盖图标 -->
                <div v-if="videoStates[index] === 'paused'" class="play-overlay">
                  <Icon name="zantingtubiao" color="#fff" size="32" />
                </div>
              </div>

              <!-- 互动操作：点赞、评论、分享 -->
              <div class="post-actions">
                <div class="action-item" @click="handleDynamicClickLike(item.videoId)">
                  <Icon name="xin-2" :color="item.isLiked ? '#ff4d4f' : '#ccc'" size="20" />
                  <span class="count">{{ item.likeNum }}</span>
                </div>
                <div class="action-item" @click="handleClickComment(item.videoId)">
                  <Icon name="pinglun" color="#fff" size="20" />
                  <span class="count">{{ item.commentNum }}</span>
                </div>
                <div class="action-item">
                  <Icon name="a-fenxiangweifenxiang" color="#fff" size="18" />
                  <span class="count">{{ item.shareNum }}</span>
                </div>
              </div>

              <!-- 发布时间 -->
              <div class="post-time">{{ item.createdAt }}</div>
            </div>

            <!-- 评论弹窗 -->
            <CommentModal v-if="showCommentModal" v-model="showCommentModal" :videoId="videoCommentsVideoId" />
          </div>
        </TabItem>

        <!-- Tab 3: 喜欢 -->
        <TabItem :title="`喜欢${likeVideoNum}`">
          <!-- 加载中 -->
          <div v-if="tabLoading.like" class="tab-loading">
            <span class="icon">
              <Icon name="jiazailoadding" color="red" size="24" />
            </span>
            <span>加载中...</span>
          </div>
          <!-- 无数据或超时 -->
          <div v-else-if="tabTimeout.like || likeList.length === 0" class="tab-no-data">暂无喜欢</div>

          <!-- 已有数据 -->
          <div v-else>
            <div ref="likeContainerRef" class="like-container" @scroll="onLikeScroll">
              <div class="tab_list">
                <div class="tab_list_item" v-for="(item, index) in likeList" :key="item.videoId"
                  @click="handleClickLike(index)">
                  <img :src="item.videoCover" alt="" />
                  <div class="tab_list_item__like">
                    <Icon name="aixin" size="14" color="#fff" />
                    <span>{{ item.likeNum }}</span>
                  </div>
                </div>
              </div>

              <!-- 分页加载提示 -->
              <div v-if="loading && likeList.length > 0" class="loading-more">
                <Icon name="jiazailoadding" color="red" size="16" /> 加载中...
              </div>
              <div v-else-if="!hasMore && likeList.length > 0" class="no-more">暂无更多喜欢</div>
            </div>
          </div>
        </TabItem>
      </Tab>
    </div>

    <!-- 竖屏视频播放组件（模态层） -->
    <transition name="fade-left">
      <VerticalFeed v-if="showVerticalFeed" v-model="showVerticalFeed" :currentIndex="currentVideoIndex"
        :feedData="VideoList" />
    </transition>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, reactive, defineAsyncComponent, watch, inject } from 'vue'
import Icon from '@/components/common/Icon.vue'
import Navbar from '@/components/common/Navbar.vue'
import { formatTimeAgo } from '@/utils/time'
const socket = inject('socket')

// 工具函数
import { Toast } from '@/utils/showtoast'

// API 请求方法
import { getFriendUserInfoAPI, getFriendUserVideosAPI, followFriendUserAPI } from '@/api/search'
import {
  getWorkListAPI,
  getDynamicListAPI,
  getDynamicVideoLikeStatusAPI,
  getLikeListAPI,
  postVideoLikeAPI,
  getFollowNumAPI,
  getFanNumAPI,
  getLikeNumAPI,
  getLikeVideoNumAPI,
  getDynamicNumAPI
} from '@/api/my'


// 路由相关
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()

// 当前访问的用户 ID（来自路由参数）
const CurrentUserId = computed(() => route.query.userId)

// 用户登录信息（从 Pinia store 获取）
import { useUserStore } from '@/stores/userinfo'
const userInfo = useUserStore()
const user = computed(() => userInfo.userInfo)

// 计算属性：当前用户基础信息
const userId = computed(() => user.value?.userId)


// 👉 好友用户信息（被查看的人）
const friendUserInfo = ref({})
const getFriendUserInfo = async () => {
  try {
    const res = await getFriendUserInfoAPI(CurrentUserId.value, userId.value)
    if (res.code === 200) {
      // res.data.userAvatar = 'http://43.138.15.137:3000' + res.data.userAvatar
      res.data.userAvatar = res.data.userAvatar.startsWith('http')
        ? res.data.userAvatar
        : 'http://43.138.15.137:3000' + res.data.userAvatar
      friendUserInfo.value = res.data || {}
    }
  } catch (error) {
    console.error('获取好友信息失败:', error)
  }
}

// 👉 好友发布的视频列表（用于点击“作品”跳转播放）
const friendUserVideos = ref([])
const getFriendUserVideos = async () => {
  try {
    const res = await getFriendUserVideosAPI(CurrentUserId.value)
    if (res.code === 200) {
      // 合并 Video 和 WSLCNum 数据
      const mergeList = res.data.map(item => ({
        ...item.Video,
        ...item.WSLCNum,
        userAvatar: item.Video.userAvatar.startsWith('http')
          ? item.Video.userAvatar
          : 'http://43.138.15.137:3000' + item.Video.userAvatar
      }))
      friendUserVideos.value = mergeList || []
      console.log('好友视频列表:', friendUserVideos.value)
    }
  } catch (error) {
    console.error('获取好友视频列表失败:', error)
  }
}

// 导入 Tab 组件
import Tab from '@/components/common/Tab.vue'
import TabItem from '@/components/common/TabItem.vue'

// -----------------------------
// 🔹 Tab 相关状态管理
// -----------------------------

// 强制刷新 Tab 组件的 key（避免缓存问题）
const tabKey = ref(0)

// 缓存标记：记录各 Tab 是否已加载过一次
const tabLoaded = reactive({
  work: false,
  dynamic: false,
  like: false
})

// 加载状态（是否正在请求）
const tabLoading = reactive({
  work: false,
  dynamic: false,
  like: false
})

// 超时状态（超过 5 秒未响应）
const tabTimeout = reactive({
  work: false,
  dynamic: false,
  like: false
})
const TIMEOUT_DURATION = 5000 // 5秒超时

// -----------------------------
// 📁 数据请求函数
// -----------------------------

// 获取“作品”列表
const workList = ref([])
const getWorkList = async () => {
  try {
    const res = await getWorkListAPI(CurrentUserId.value)
    const mergedList = res.data.map(item => ({
      ...item.Video,
      ...item.WSLCNum
    })).map(item => {
      item.userAvatar = 'http://43.138.15.137:3000' + item.userAvatar
      return item
    })
    workList.value = mergedList
  } catch (error) {
    console.error('获取作品失败:', error)
  } finally {
    tabKey.value += 1 // 强制刷新 Tab
  }
}

// 获取“动态”列表
const dynamicList = ref([])
const getDynamicList = async () => {
  try {
    const res = await getDynamicListAPI(CurrentUserId.value)
    if (!res.data?.length) {
      dynamicList.value = []
      tabKey.value += 1
      return
    }

    let mergedList = res.data.map(item => ({
      ...item.Video,
      ...item.WSLCNum,
      createdAt: formatTimeAgo(item.Video.createdAt)
    })).map(item => {
      item.userAvatar = 'http://43.138.15.137:3000' + item.userAvatar
      return item
    })

    // 并发获取每条动态的点赞状态
    const likeStatusPromises = mergedList.map(item =>
      getDynamicVideoLikeStatusAPI(userId.value, item.videoId)
        .then(res => res.data)
        .catch(() => false)
    )
    const likeStatusList = await Promise.all(likeStatusPromises)

    mergedList = mergedList.map((item, index) => ({
      ...item,
      isLiked: likeStatusList[index]
    }))

    dynamicList.value = mergedList
  } catch (error) {
    console.error('获取动态失败:', error)
    dynamicList.value = []
  } finally {
    tabKey.value += 1
  }
}

// 获取“喜欢”列表（支持分页）
const likeList = ref([])
const page = ref(1)
const hasMore = ref(true)
const loading = ref(false)

// 获取喜欢列表数据
const getLikeList = async (isLoadMore = false) => {
  if (loading.value || !hasMore.value) return
  loading.value = true

  try {
    const res = await getLikeListAPI(CurrentUserId.value, page.value)

    if (!res.data?.length) {
      hasMore.value = false
    } else {
      const mergedList = res.data.map(item => ({
        ...item.Video,
        ...item.WSLCNum,
        userAvatar: 'http://43.138.15.137:3000' + item.Video.userAvatar
      }))

      likeList.value = isLoadMore
        ? [...likeList.value, ...mergedList]
        : mergedList

      // 若返回数量不足一页，则认为没有更多了
      hasMore.value = res.data.length >= 10
    }

    if (!isLoadMore) tabKey.value += 1
  } catch (error) {
    console.error('获取喜欢失败:', error)
    hasMore.value = false
  } finally {
    loading.value = false
  }
}

// 滚动加载更多（喜欢列表专用）
const likeContainerRef = ref(null)
const onLikeScroll = () => {
  if (loading.value || !hasMore.value || !likeContainerRef.value) return
  const el = likeContainerRef.value
  if (el.scrollHeight - el.scrollTop <= el.clientHeight + 20) {
    page.value++
    getLikeList(true)
  }
}

// Tab 切换事件处理
const handleTabChange = (index) => {
  switch (index) {
    case 0: if (!tabLoaded.work && !tabLoading.work) loadWorkTab(); break
    case 1: if (!tabLoaded.dynamic && !tabLoading.dynamic) loadDynamicTab(); break
    case 2: if (!tabLoaded.like && !tabLoading.like) loadLikeTab(); break
  }
}

// 封装 Tab 加载逻辑（带超时机制）
const loadWorkTab = async () => {
  tabLoading.work = true
  tabTimeout.work = false
  const timeoutId = setTimeout(() => { tabTimeout.work = true; tabLoading.work = false }, TIMEOUT_DURATION)
  try {
    await getWorkList()
    clearTimeout(timeoutId)
    tabLoaded.work = true
  } catch (e) { /* 忽略 */ } finally {
    tabLoading.work = false
  }
}

const loadDynamicTab = async () => {
  tabLoading.dynamic = true
  tabTimeout.dynamic = false
  const timeoutId = setTimeout(() => { tabTimeout.dynamic = true; tabLoading.dynamic = false }, TIMEOUT_DURATION)
  try {
    await getDynamicList()
    clearTimeout(timeoutId)
    tabLoaded.dynamic = true
  } catch (e) { /* 忽略 */ } finally {
    tabLoading.dynamic = false
  }
}

const loadLikeTab = async () => {
  tabLoading.like = true
  tabTimeout.like = false
  const timeoutId = setTimeout(() => { tabTimeout.like = true; tabLoading.like = false }, TIMEOUT_DURATION)
  try {
    await getLikeList()
    clearTimeout(timeoutId)
    tabLoaded.like = true
  } catch (e) { /* 忽略 */ } finally {
    tabLoading.like = false
  }
}

// 页面初始化：并行加载所有数据
onMounted(async () => {


  try {
    await Promise.all([
      // 用户信息
      getFriendUserInfo(),
      // 用户作品
      getFriendUserVideos(),
      // 获赞
      getLikeNum(),
      // 粉丝数量
      getFanNum(),
      // 关注数量
      getFollowNum(),
      // 喜欢数量
      getLikeVideoNum(),
      // 动态数量
      getDynamicNum()
    ])
    tabKey.value += 1
  } catch (error) {
    console.error('初始化失败:', error)
  }
})

// -----------------------------
// ▶️ 视频播放控制（动态中的视频）
// -----------------------------
const videoStates = ref({}) // 存储每个视频的状态：idle / playing / paused
const videoRefs = ref([])   // DOM 引用集合

const togglePlay = async (index) => {
  const video = videoRefs.value[index]
  if (!video) return

  const currentState = videoStates.value[index] || 'idle'

  if (currentState === 'playing') {
    video.pause()
    videoStates.value[index] = 'paused'
  } else {
    // 暂停其他所有视频
    videoRefs.value.forEach((v, i) => {
      if (v && i !== index) {
        v.pause()
        videoStates.value[i] = 'idle'
      }
    })

    try {
      await video.play()
      videoStates.value[index] = 'playing'
    } catch (err) {
      console.warn('播放失败:', err)
      videoStates.value[index] = 'idle'
    }
  }
}

// -----------------------------
// 🖱️ 背景图下拉放大交互
// -----------------------------
const backgroundHeight = ref(150) // 初始高度
const backgroundScale = ref(1) // 添加缩放比例变量
const backgroundOpacity = ref(1) // 添加透明度变量
const isDragging = ref(false)
const startY = ref(0)
const currentY = ref(0)
const dragThreshold = 5 // 判断是拖拽还是点击的阈值
const scrollThreshold = 50 // 判断是否在顶部的阈值
let initialScrollTop = 0 // 记录初始滚动位置
let animationFrameId = null // 用于动画帧ID
let lastTimestamp = 0 // 用于计算动画时间差
let velocity = 0 // 用于记录拖拽速度

const handleTouchStart = (e) => {
  // 取消任何正在进行的动画
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
    animationFrameId = null
  }
  
  startY.value = e.touches[0].clientY
  isDragging.value = false
  initialScrollTop = window.pageYOffset || document.documentElement.scrollTop
  lastTimestamp = Date.now()
  velocity = 0
}

const handleTouchMove = (e) => {
  currentY.value = e.touches[0].clientY
  const deltaY = currentY.value - startY.value
  const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop
  
  // 计算时间差和速度
  const currentTime = Date.now()
  const timeDiff = currentTime - lastTimestamp
  if (timeDiff > 0) {
    velocity = deltaY / timeDiff
    lastTimestamp = currentTime
  }

  // 判断是否在页面顶部且向下拖拽
  if (currentScrollTop <= scrollThreshold && deltaY > dragThreshold) {
    // 在顶部且向下拖拽，标记为拖拽状态
    isDragging.value = true
    
    // 使用更自然的阻尼算法
    // 前段使用较小的阻尼，后段使用较大的阻尼
    let dampingFactor
    if (deltaY < 100) {
      // 前段：线性增长，阻尼较小
      dampingFactor = 0.5
    } else {
      // 后段：使用对数增长，阻尼逐渐增大
      dampingFactor = 0.5 + (Math.log(deltaY / 100) * 0.15)
      dampingFactor = Math.min(dampingFactor, 0.85) // 限制最大阻尼
    }
    
    const adjustedDeltaY = deltaY * dampingFactor
    const newHeight = Math.min(150 + adjustedDeltaY, 350) // 限制最大高度为350px
    backgroundHeight.value = newHeight
    
    // 计算缩放比例，基于高度变化，使用更平滑的曲线
    const heightRatio = Math.pow((newHeight - 150) / 200, 0.8) // 使用幂函数使变化更平滑
    backgroundScale.value = 1 + heightRatio * 0.25 // 增加缩放比例，确保填充整个区域
    
    // 添加透明度变化，增加层次感
    backgroundOpacity.value = Math.max(0.85, 1 - (heightRatio * 0.15))
  }
}

const handleTouchEnd = () => {
  if (!isDragging.value) return
  
  // 使用速度来决定回弹动画的时长和缓动
  const duration = Math.min(600, Math.max(300, Math.abs(velocity) * 50))
  
  // 使用requestAnimationFrame实现平滑回弹动画
  const startTime = performance.now()
  const startHeight = backgroundHeight.value
  const startScale = backgroundScale.value
  const startOpacity = backgroundOpacity.value
  
  // 使用自定义缓动函数，模拟弹性回弹
  const easeOutElastic = (t) => {
    const p = 0.3
    return Math.pow(2, -10 * t) * Math.sin((t - p / 4) * (2 * Math.PI) / p) + 1
  }
  
  const animate = (currentTime) => {
    const elapsed = currentTime - startTime
    const progress = Math.min(elapsed / duration, 1)
    
    // 应用缓动函数
    const easedProgress = easeOutElastic(progress)
    
    // 更新值
    backgroundHeight.value = startHeight + (150 - startHeight) * easedProgress
    backgroundScale.value = startScale + (1 - startScale) * easedProgress
    backgroundOpacity.value = startOpacity + (1 - startOpacity) * easedProgress
    
    if (progress < 1) {
      animationFrameId = requestAnimationFrame(animate)
    } else {
      // 确保最终值正确
      backgroundHeight.value = 150
      backgroundScale.value = 1
      backgroundOpacity.value = 1
      animationFrameId = null
    }
  }
  
  animationFrameId = requestAnimationFrame(animate)
  isDragging.value = false
}

// 鼠标事件（桌面端兼容）
const handleMouseDown = (e) => {
  // 取消任何正在进行的动画
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
    animationFrameId = null
  }
  
  startY.value = e.clientY
  isDragging.value = false
  initialScrollTop = window.pageYOffset || document.documentElement.scrollTop
  lastTimestamp = Date.now()
  velocity = 0
  document.addEventListener('mousemove', handleDocumentMouseMove)
  document.addEventListener('mouseup', handleDocumentMouseUp)
}

const handleDocumentMouseMove = (e) => {
  currentY.value = e.clientY
  const deltaY = currentY.value - startY.value
  const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop
  
  // 计算时间差和速度
  const currentTime = Date.now()
  const timeDiff = currentTime - lastTimestamp
  if (timeDiff > 0) {
    velocity = deltaY / timeDiff
    lastTimestamp = currentTime
  }

  // 判断是否在页面顶部且向下拖拽
  if (currentScrollTop <= scrollThreshold && deltaY > dragThreshold) {
    isDragging.value = true
    
    // 使用更自然的阻尼算法
    // 前段使用较小的阻尼，后段使用较大的阻尼
    let dampingFactor
    if (deltaY < 100) {
      // 前段：线性增长，阻尼较小
      dampingFactor = 0.5
    } else {
      // 后段：使用对数增长，阻尼逐渐增大
      dampingFactor = 0.5 + (Math.log(deltaY / 100) * 0.15)
      dampingFactor = Math.min(dampingFactor, 0.85) // 限制最大阻尼
    }
    
    const adjustedDeltaY = deltaY * dampingFactor
    const newHeight = Math.min(150 + adjustedDeltaY, 350) // 限制最大高度为350px
    backgroundHeight.value = newHeight
    
    // 计算缩放比例，基于高度变化，使用更平滑的曲线
    const heightRatio = Math.pow((newHeight - 150) / 200, 0.8) // 使用幂函数使变化更平滑
    backgroundScale.value = 1 + heightRatio * 0.25 // 增加缩放比例，确保填充整个区域
    
    // 添加透明度变化，增加层次感
    backgroundOpacity.value = Math.max(0.85, 1 - (heightRatio * 0.15))
    
    // 阻止默认行为，防止页面滚动
    if (e.target.closest('.profile')) {
      e.preventDefault()
    }
  }
}

const handleDocumentMouseUp = () => {
  document.removeEventListener('mousemove', handleDocumentMouseMove)
  document.removeEventListener('mouseup', handleDocumentMouseUp)
  
  if (!isDragging.value) return
  
  // 使用速度来决定回弹动画的时长和缓动
  const duration = Math.min(600, Math.max(300, Math.abs(velocity) * 50))
  
  // 使用requestAnimationFrame实现平滑回弹动画
  const startTime = performance.now()
  const startHeight = backgroundHeight.value
  const startScale = backgroundScale.value
  const startOpacity = backgroundOpacity.value
  
  // 使用自定义缓动函数，模拟弹性回弹
  const easeOutElastic = (t) => {
    const p = 0.3
    return Math.pow(2, -10 * t) * Math.sin((t - p / 4) * (2 * Math.PI) / p) + 1
  }
  
  const animate = (currentTime) => {
    const elapsed = currentTime - startTime
    const progress = Math.min(elapsed / duration, 1)
    
    // 应用缓动函数
    const easedProgress = easeOutElastic(progress)
    
    // 更新值
    backgroundHeight.value = startHeight + (150 - startHeight) * easedProgress
    backgroundScale.value = startScale + (1 - startScale) * easedProgress
    backgroundOpacity.value = startOpacity + (1 - startOpacity) * easedProgress
    
    if (progress < 1) {
      animationFrameId = requestAnimationFrame(animate)
    } else {
      // 确保最终值正确
      backgroundHeight.value = 150
      backgroundScale.value = 1
      backgroundOpacity.value = 1
      animationFrameId = null
    }
  }
  
  animationFrameId = requestAnimationFrame(animate)
  isDragging.value = false
}

// -----------------------------
// 📺 视频播放页跳转
// -----------------------------
const showVerticalFeed = ref(false)
const VerticalFeed = defineAsyncComponent(() => import('@/components/common/VerticalFeed.vue'))

const VideoList = ref([])
const currentVideoIndex = ref(0)

const handleClickWork = (index) => {
  showVerticalFeed.value = true
  currentVideoIndex.value = index
  VideoList.value = friendUserVideos.value
}

const handleClickLike = (index) => {
  showVerticalFeed.value = true
  currentVideoIndex.value = index
  VideoList.value = likeList.value
}

// -----------------------------
// 💬 评论弹窗
// -----------------------------
const CommentModal = defineAsyncComponent(() => import('@/components/common/CommentModal.vue'))
const showCommentModal = ref(false)
const videoCommentsVideoId = ref('')

const handleClickComment = (videoId) => {
  videoCommentsVideoId.value = videoId
  showCommentModal.value = true
}

// -----------------------------
// ❤️ 动态点赞
// -----------------------------
const handleDynamicClickLike = async (videoId) => {
  try {
    const res = await postVideoLikeAPI(userId.value, videoId)
    if (res.code === 200) {
      const item = dynamicList.value.find(v => v.videoId === videoId)
      if (item) {
        item.isLiked = !item.isLiked
        item.isLiked ? item.likeNum++ : item.likeNum--
      }
    }
  } catch (error) {
    console.error('点赞失败:', error)
  }
}

// -----------------------------
// 📊 数量统计请求
// -----------------------------
const followNum = ref(0)
const getFollowNum = async () => {
  try {
    const res = await getFollowNumAPI(CurrentUserId.value)
    if (res.code === 200) followNum.value = res.data
  } catch (error) { console.error('关注数获取失败:', error) }
}

const fanNum = ref(0)
const getFanNum = async () => {
  try {
    const res = await getFanNumAPI(CurrentUserId.value)
    if (res.code === 200) fanNum.value = res.data
  } catch (error) { console.error('粉丝数获取失败:', error) }
}

const likeNum = ref(0)
const getLikeNum = async () => {
  try {
    const res = await getLikeNumAPI(CurrentUserId.value)
    if (res.code === 200) likeNum.value = res.data
  } catch (error) { console.error('获赞数获取失败:', error) }
}

const likeVideoNum = ref(0)
const getLikeVideoNum = async () => {
  try {
    const res = await getLikeVideoNumAPI(CurrentUserId.value)
    if (res.code === 200) likeVideoNum.value = res.data
  } catch (error) { console.error('喜欢视频数获取失败:', error) }
}

const dynamicNum = ref(0)
const getDynamicNum = async () => {
  try {
    const res = await getDynamicNumAPI(CurrentUserId.value)
    if (res.code === 200) dynamicNum.value = res.data
  } catch (error) { console.error('动态数获取失败:', error) }
}

// 返回上一页
const handleBack = () => router.go(-1)


// 关注 / 取消关注
const handlfollowUser = async () => {
  try {
    const res = await followFriendUserAPI(userId.value, CurrentUserId.value)
    console.log('关注/取消关注操作结果:', res)
    // 更新UI
    if (res.code === 200) {
      if (friendUserInfo.value.myRelation === 'none') {
        friendUserInfo.value.myRelation = 'follow'
        followNum.value += 1
        Toast('关注成功', {
          position: 'bottom'
        })
      } else if (friendUserInfo.value.myRelation === 'follow') {
        friendUserInfo.value.myRelation = 'none'
        followNum.value -= 1
        Toast('已取消关注', {
          position: 'bottom'
        })
      } else if (friendUserInfo.value.myRelation === 'both') {
        friendUserInfo.value.myRelation = 'follower'
        followNum.value -= 1
        Toast('已取消关注', {
          position: 'bottom'
        })
      } else if (friendUserInfo.value.myRelation === 'follower') {
        friendUserInfo.value.myRelation = 'both'
        followNum.value += 1
        Toast('关注成功', {
          position: 'bottom'
        })
      }
      // 通知发送事件
      socket.emit('sendTriggerFollow', {
        toUserId: CurrentUserId.value
      })
      console.log('关注/取消关注事件已发送')

    } else {
      Toast(res.message || '操作失败，请稍后重试', {
        position: 'bottom'
      })
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    Toast('操作失败，请稍后重试', {
      position: 'bottom'
    })
  }
}
// 跳转到TA的关注列表
const handleGoTAfollow = () => {
  router.push({
    name: 'TAFollowings', query: {
      userId: CurrentUserId.value
    }
  })
}
// 跳转到TA的粉丝列表
const handleGoTAfans = () => {
  router.push({
    name: 'TAFans', query: {
      userId: CurrentUserId.value
    }
  })
}


</script>


<style lang="scss" scoped>
.my {
  @include fixed-top;
  overflow: hidden;
  overflow-y: auto;
  width: 100%;
  height: 100%;
  /* 防止内容溢出影响其他元素 */
  isolation: isolate;
  /* 创建新的层叠上下文，防止影响其他固定定位元素 */
  /* 确保背景图片缩放时不会出现缝隙 */
  background-color: #161622; /* 添加背景色，防止缩放时露出底层 */

  // 定位右上角
  .title_background__more {
    width: 32px;
    height: 32px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;

    .EditExit {
      position: absolute;
      top: 100px;
      right: 0;
      width: 80px;
      height: 80px;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 2px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      color: #fff;
      z-index: 222;
      opacity: 0;
      visibility: hidden;
      transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);

      &.active {
        top: 40px;
        opacity: 1;
        visibility: visible;

      }

      &::after {
        display: block;
        position: absolute;
        top: -15px;
        right: 8px;
        border: 8px solid transparent;
        border-bottom: 8px solid rgba(0, 0, 0, 0.5);
        content: '';
      }

      .EditExit__item {
        flex: 1;
        -webkit-box-flex: 1;
        height: 44px;
        line-height: 44px;
        height: 44px;
        width: 100%;
        text-align: center;
      }

    }
  }
}

.my_title_background {
  width: 100%;
  height: 150px;
  /* 默认高度，会被动态样式覆盖 */
  position: relative;
  overflow: hidden;
  transition: opacity 0.1s ease-out; /* 只对透明度应用过渡，其他属性由JS控制 */
  transform-origin: center top;
  z-index: 1;
  /* 确保背景在正确的层级，不影响其他元素 */
  will-change: transform, opacity; /* 提示浏览器优化这些属性 */
  /* 确保背景始终填满容器，不出现缝隙 */
  backface-visibility: hidden; /* 防止缩放时出现闪烁 */
  /* 确保背景图片缩放时不会出现缝隙 */
  margin-bottom: -1px; /* 消除与下方内容的间隙 */


  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.1s ease-out; /* 对图片应用轻微过渡效果 */
    /* 确保图片在缩放时不会出现缝隙 */
    transform-origin: center center;
    backface-visibility: hidden;
    /* 确保图片始终填充容器，不留空白 */
    min-width: 100%;
    min-height: 100%;
  }
}

.profile {
  position: relative;
  width: 100%;
  background: #161622;
  transition-timing-function:
    cubic-bezier(0.165, 0.84, 0.44, 1);
  transition-duration: 0ms;
  transform: translate(0px, 0px) scale(1) translateZ(0px);
  z-index: 2;
  /* 确保内容在背景之上 */
  isolation: isolate;
  /* 创建新的层叠上下文，防止影响其他元素 */

  .avatar_wrap {
    position: absolute;
    left: 10px;
    top: -15px;
    border-radius: 50%;
    padding: 5px;
    width: 80px;
    height: 80px;
    background: #161622;

    img {
      border-radius: 50%;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .name_wrap {
    position: relative;
    margin: 0 10px;
    padding: 80px 10px 10px;
    border-bottom: 1px solid rgba(41, 40, 37, 0.8);

    .name {
      color: #fff;
      font-size: 18px;
    }

    .subname {
      margin-top: 5px;
      color: #fff;
      font-size: 12px;
    }

    .foolw {
      @include absolute-top-right(20px);
      width: 60px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      border-radius: 6px;
      font-size: 12px;
      color: #fff;
      background-color: #f9355f;

      &.active {
        background-color: rgba(255, 255, 255, 0.1);
      }
    }
  }

  .desc_wrap {
    margin: 10px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    gap: 15px;

    .desc_wrap_info {
      display: flex;
      gap: 5px;
      align-items: center;

      .gender {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 2px 8px;
        border-radius: 5px;
        background: rgba(67, 51, 63, 0.7);
        font-size: 10px;
        max-width: 50px;
        color: #8b8c96;
        white-space: nowrap;
      }

      .desc_wrap_info_age {
        font-size: 12px;
        color: #8b8c96;

      }

      .desc_wrap_info_address {
        font-size: 12px;
        color: #8b8c96;
      }


    }

    .desc {
      color: #8b8c96;
      font-size: 12px;
    }


  }

  .num_wrap {
    margin: 10px;
    width: 200px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    color: #fff;

    .li {
      font-size: 14px;
    }
  }

  .tab_list {
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 46px;

    .tab_list_item {
      position: relative;
      width: 33.33%;
      height: 160px;
      border: 1px solid #000;


      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .tab_list_item__delete {
        position: absolute;
        top: 0;
        right: 2px;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .tab_list_item__like {
        position: absolute;
        bottom: 2px;
        left: 6px;
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        color: #fff;
        gap: 2px;
      }
    }
  }

  .commit_list_wrap_more {
    text-align: center;
    font-size: 12px;
    color: #65676e;
    margin: 14px 0;
  }

  .follow {
    background-color: #161622;
    padding-bottom: 48px;

    .follow_item {
      width: 98%;
      margin: 10px auto 0;
      display: flex;
      flex-direction: column;
      gap: 10px;
      border-bottom: 1px solid #252425;
      padding: 5px;

      .follow_item_top {
        display: flex;
        align-items: center;
        gap: 5px;

        .follow_item_top__avatar {
          width: 30px;
          height: 30px;
          border-radius: 50%;
        }

        .follow_item_top__username {
          font-size: 14px;
          color: #fff;
        }
      }

      .follow_item_desc {
        font-size: 14px;
        color: #fff;
      }

      .follow_item_video {
        width: 250px;
        height: 350px;
      }

      .follow_item_bar {
        display: flex;
        gap: 10px;

        .follow_item_bar_item {
          display: flex;
          align-items: center;
          gap: 5px;

          font-size: 14px;
          color: #fff;
        }
      }

      .follow_item_time {
        font-size: 12px;
        color: #fff;
      }
    }
  }
}

// 从左到右过渡出现
.fade-in-right-enter-active,
.fade-in-right-leave-active {
  transition: all 0.3s ease-in-out;
}

.fade-in-right-enter-from,
.fade-in-right-leave-to {
  transform: translateX(100%);
  opacity: 0;
}

.follow-page {
  background-color: $secondary-color;
  color: white;
  min-height: 100vh;
  margin-bottom: $spacing-xl;

  .post-item {
    background-color: $bg-color;
    border-radius: 12px;
    padding: 14px;
    margin-bottom: $spacing-lg;

    .post-header {
      @include flex-center;
      gap: 8px;
      margin-bottom: 8px;
      justify-content: start;

      .avatar {
        width: 35px;
        height: 35px;
        border-radius: 50%;
      }

      .username {
        font-size: $font-size-base;
        font-weight: 500;
      }
    }

    .post-meta {
      font-size: $font-size-base;
      color: $comment-modal-border-color;
      margin-bottom: $spacing-md;
    }

    .post-media {
      position: relative;

      overflow: hidden;
      width: 80%;
      height: 400px;
      border-radius: $border-radius-md;
      background-color: $black-color;

      .play-overlay {
        width: 100%;
        height: 100%;
        @include absolute-top-right;
        @include flex-center;
      }

      .media-video {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .post-actions {
      width: 80%;
      @include flex-around;
      margin: $spacing-md 0;
      gap: $spacing-lg;

      .action-item {
        @include flex-center;
        color: $comment-modal-border-color;
        font-size: $font-size-small;
        gap: 5px;
      }
    }
  }
}






.like-container {
  height: calc(100vh - 200px); // 根据你的布局调整
  padding-bottom: 46px;
  overflow-y: auto;
}

.loading-more,
.no-more,
.no-data {
  text-align: center;
  padding: 12px;
  color: #999;
  font-size: 14px;
}




.icon-heart {
  color: #ff4d4d;
}

.post-time {
  font-size: $font-size-small;
  color: #999;
  margin-top: $spacing-md;
}

/* 评论区 */
.comment-section {
  margin-top: 16px;
}

.comment-item {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-username {
  font-size: 14px;
  font-weight: 500;
}

.tab-loading,
.tab-no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
  font-size: 14px;
}

.tab-loading .icon {
  margin-bottom: 8px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>